﻿using System;
using System.Windows.Forms;
using SSISComponents.ReportGenerator.ReportService2005;
using Microsoft.VisualBasic;

namespace SSISComponents.ReportGenerator
{
    public partial class ReportProperties : Form
    {
        
        private string _Reportname = null;
        private string _ReportServer = null;
        private string _Username = null;
        private string _Password = null;
        private bool _WindowsAuthorization = false;
        private CatalogItem _Item = null;
        ReportService2005.ReportingService2005 rs;

        /// <summary>
        /// 
        /// </summary>
        public CatalogItem Item
        {
            get { return _Item; }
            set { _Item = value; }
        }

        /// <summary>
        /// 
        /// </summary>
        public string Reportname
        {
            get { return _Reportname; }
            set { _Reportname = value; }
        }

        /// <summary>
        /// 
        /// </summary>
        public string ReportServer
        {
            get { return _ReportServer; }
            set { _ReportServer = value; }
        }

        /// <summary>
        /// 
        /// </summary>
        public string Username
        {
            get { return _Username; }
            set { _Username = value; }
        }

        /// <summary>
        /// 
        /// </summary>
        public string Password
        {
            get { return _Password; }
            set { _Password = value; }
        }

        /// <summary>
        /// 
        /// </summary>
        public bool WindowsAuthorization
        {
            get { return _WindowsAuthorization; }
            set { _WindowsAuthorization = value; }
        }
        
        public ReportProperties()
        {
            InitializeComponent();
        }

        private void ReportProperties_Load(object sender, EventArgs e)
        {
            rs = new ReportService2005.ReportingService2005();
            rs.Credentials = System.Net.CredentialCache.DefaultCredentials;
            rs.Url = ReportServer + "/ReportService2005.asmx";
            
            txtErstelltVon.Text = IsNull(_Item.CreatedBy);
            txtErstelltAm.Text = IsNull(_Item.CreationDate);
            txtBeschreibung.Text = IsNull(_Item.Description);
            txtID.Text = "{" + IsNull(_Item.ID) + "}";
            txtGeaendertVon.Text = IsNull(_Item.ModifiedBy);
            txtGeaendertAm.Text = IsNull(_Item.ModifiedDate);
            txtName.Text = IsNull(_Item.Name);
            //txtOrt.Text = IsNull(_Item.Path);
            if (IsNull(Item.Hidden) == "True")
            {
                cbVersteckt.Checked = true;
            }
            else
            {
                cbVersteckt.Checked = false;
            }

            if (Information.IsNumeric(IsNull(Item.Size)))
            {
                this.txtGroesse.Text = Strings.FormatNumber((Item.Size / 1024), 2, TriState.UseDefault, TriState.UseDefault, TriState.UseDefault).ToString() + " KB";
            }
            else
            {
                this.txtGroesse.Text = IsNull(_Item.Size);
            }

            switch (Item.Type)
            {
                case ItemTypeEnum.Folder:
                    tabControl1.TabPages.Remove(tabControl1.TabPages["tpSnapshots"]);
                    tabControl1.TabPages.Remove(tabControl1.TabPages["tpDatasource"]);
                    tabControl1.TabPages.Remove(tabControl1.TabPages["tpParameter"]);
                    tabControl1.TabPages.Remove(tabControl1.TabPages["tpSicherheit"]);
                    break;
                case ItemTypeEnum.Report:
                    FillSecurity();
                    FillParameter();
                    FillDataSource();
                    FillSnapshots();
                    break;
                case ItemTypeEnum.DataSource:
                    break;
                case ItemTypeEnum.LinkedReport:
                    break;
                case ItemTypeEnum.Model:
                    break;
                case ItemTypeEnum.Resource:
                    break;
                case ItemTypeEnum.Unknown:
                    break;
            }
        }

        /// <summary>
        /// get report data source
        /// </summary>
        private void FillDataSource()
        {
            try
            {
                lvDataSource.Items.Clear();
                //string[] strPermissions = rs.GetPermissions(_Item.Path.ToString());
                DataSource[] ds = rs.GetItemDataSources(_Item.Path.ToString());
                for (int i = 0; i < ds.Length; i++)
                {
                    DataSourceReference dsref = (DataSourceReference)ds[i].Item;
                    ListViewItem li = new ListViewItem();
                    li.Text = ds[i].Name;
                    li.Tag = ds[i];
                    li.SubItems.Add(dsref.Reference);
                    li.ImageKey = "Database";
                    lvDataSource.Items.Add(li);
                }
            }
            catch { }
        }

        /// <summary>
        /// get report parameter
        /// </summary>
        private void FillParameter()
        {
            try
            {
                ReportParameter[] Parameter = rs.GetReportParameters(_Item.Path, null, false, null, null);
                for (int i = 0; i < Parameter.Length; i++)
                {
                    ListViewItem li = new ListViewItem();
                    li.Name = Parameter[i].Name;
                    li.Text = Parameter[i].Name;
                    li.SubItems.Add(Parameter[i].Type.ToString());
                    li.SubItems.Add(Parameter[i].Nullable.ToString());
                    li.SubItems.Add(Parameter[i].State.ToString());
                    li.ImageKey = "Parameter";
                    lvParameter.Items.Add(li);
                }
            }
            catch { }
        }

        /// <summary>
        /// get security information
        /// </summary>
        private void FillSecurity()
        {
            try
            {
                bool wahr = true;
                lvSecurity.Items.Clear();
                //string[] strPermissions = rs.GetPermissions(_Item.Path);
                Policy[] Policies = rs.GetPolicies(_Item.Path.ToString(), out wahr);
                for (int i = 0; i < Policies.Length; i++)
                {
                    ListViewItem li = new ListViewItem();
                    li.Name = Policies[i].GroupUserName.ToString();
                    li.Text = Policies[i].GroupUserName.ToString();
                    li.ImageKey = "User";
                    lvSecurity.Items.Add(li);
                }
            }
            catch { }
        }

        private void FillSnapshots()
        {
            lvSnapshots.Items.Clear();
            if (rs.ListReportHistory(_Item.Path).Length > 0)
            {
                foreach (ReportHistorySnapshot x in rs.ListReportHistory(_Item.Path))
	            {
		            ListViewItem li = new ListViewItem();
                    li.Text = x.CreationDate.ToLongDateString();
                    li.Tag = x;
                    li.SubItems.Add(Strings.FormatNumber((x.Size / 1024), 2, TriState.UseDefault, TriState.UseDefault, TriState.UseDefault).ToString() + " KB");
                    li.SubItems.Add(x.HistoryID);
                    li.ImageKey = "Snapshot";
                    lvSnapshots.Items.Add(li);
	            }    
            }
            else 
            {
                lvSnapshots.Items.Add("No Snapshots available.");
            }
        }
        
        private string IsNull(Object Value) 
        {
            string ReturnValue;
            try
            {
                if (!String.IsNullOrEmpty((string)Value))
                {
                    ReturnValue = (string)Value;
                }
                else
                {
                    ReturnValue = "n/a";
                }
            }
            catch (Exception ex)
            {
                ReturnValue = "n/a";
            }
            return ReturnValue;
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void Button4_Click(object sender, EventArgs e)
        {
            try
            {
                Warning[] warn;
                rs.CreateReportHistorySnapshot(_Item.Path, out warn);
                FillSnapshots();
            }
            catch (Exception ex)
            {
                MessageBox.Show("The report snapsoht could not been created.", "ReportGenerator Task", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void Button3_Click(object sender, EventArgs e)
        {
            try
            {
             foreach (ListViewItem n in lvSnapshots.SelectedItems)
            {
        		 ReportHistorySnapshot x = (ReportHistorySnapshot)n.Tag;
                 rs.DeleteReportHistorySnapshot(_Item.Path, x.HistoryID);
            }
            FillSnapshots();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}
